# Copyright (c) 2022 Vector Informatik GmbH
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

set(gitHashFile "${CMAKE_CURRENT_BINARY_DIR}/git_hash_file")
set(gitHeadFile "${CMAKE_CURRENT_BINARY_DIR}/git_head_file")

configure_file("@GIT_HEAD_FILE@" ${gitHeadFile} COPYONLY)

file(READ ${gitHeadFile} GIT_HEAD LIMIT 512)
string(REGEX MATCH "^ref: (.*)\n" GIT_HEAD_REF ${GIT_HEAD})

set(linkedHeadFile "${GIT_DIR}/${CMAKE_MATCH_1}")
set(linkedRef "${CMAKE_MATCH_1}")
if(GIT_HEAD_REF) 
    if(NOT EXISTS "${linkedHeadFile}")
        # the workspace might have a .git/packed-refs file instead of
        # .git/refs/heads/master
        message("-- SILKIT GIT Version: using ${GIT_DIR}/packed-refs")
        file(READ ${GIT_DIR}/packed-refs packedRefs LIMIT 4096)
        string(REGEX MATCH "([abcdef0-9]+) ${linkedRef}" headHash ${packedRefs})
        if(NOT headHash)
            message(FATAL_ERROR "MakeVersionMacros: cannot find linked git ref \"${linkedRef}\"")
        endif()
        file(WRITE ${gitHashFile} "${CMAKE_MATCH_1}\n")
    else()
        message("-- SILKIT GIT Version: using ${linkedHeadFile}")
        configure_file(
            "${linkedHeadFile}"
            ${gitHashFile}
            COPYONLY)
    endif()
else()
    configure_file(
        ${gitHeadFile}
        ${gitHashFile}
        COPYONLY)
endif()


file(READ ${gitHashFile} GIT_HEAD_HASH LIMIT 512)
string(STRIP "${GIT_HEAD_HASH}" GIT_HEAD_HASH)
message(STATUS "SILKIT GIT Version: ${GIT_HEAD_HASH}")
configure_file(
    version_macros.hpp.in
    ${CMAKE_CURRENT_BINARY_DIR}/version_macros.hpp
    @ONLY)
